//
//  ComposeViewController.swift
//  SinaWeiBo
//
//  Created by gxiangzi on 15/9/10.
//  Copyright © 2015年 hqu. All rights reserved.
//

import UIKit

class ComposeViewController: UIViewController,UITextViewDelegate {
    
    
    // 工具栏的底部
    private var toolbarBottomCons:NSLayoutConstraint?
    // 文本框的底部底部
     private var textViewBottomCons: NSLayoutConstraint?
    // 图片选择器的底部约束
    private var pictureHeightCons:NSLayoutConstraint?
    
     // MARK: -  事件的监听
    @objc private func close () {
        textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    // 发送消息
    @objc private func sendStatus() {
        // TODO: 发送消息
        let status  = textView.emoticonText;
        // 获得图片文件
        NetworkTools.sharedTools.sendStatus(status, image: pictureSelectorVC.pictures.last).subscribeNext({ (result) -> Void in
            
            printLog(result)
            
            }, error: { (error) -> Void in
                
                printLog(error)
            }) { () -> Void in
                printLog("完成发送")
                self.close()
        }
        
    }
    
    
     // MARK: - 选择图片
    @objc func  selectPicture() {
        // 1.打破 UITextView 和 ToolBar 之间的约束
        view.removeConstraint(textViewBottomCons!)
        
        // 2.新建新的约束
        textViewBottomCons = NSLayoutConstraint(item: textView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: pictureSelectorVC.view, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 0)
        view.addConstraint(textViewBottomCons!)
        
        // 更改视图
        pictureHeightCons?.constant = UIScreen.mainScreen().bounds.height * 0.6
        
        textView.resignFirstResponder()
        
        // 动画更新约束
        UIView.animateWithDuration(0.25) { () -> Void in
           self.view.layoutIfNeeded()
        }
    }
    
    ///  设置表情键盘
   @objc private func switchEmoticonKeyboard() {
        // 1.辞去 textView 的第一响应者
        textView.resignFirstResponder()
        
        // 2.设置 textView 的响应
        textView.inputView = textView.inputView == nil ? keyBoadVC.view : nil
        
        // 3.设置 textView 为第一响应者
        textView.becomeFirstResponder()
       
    }
    
    
     // MARK: - 通知
    override func viewDidLoad() {
        super.viewDidLoad()

        // 注册一个通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChanged:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
    }
    
    // 移除通知
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    // MARK: - UITextViewDelegate
    func textViewDidChange(textView: UITextView) {
        placeholderLabel.hidden = textView.hasText()
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
    // MARK: - 通知事件的响应
    @objc private func keyboardChanged(notification:NSNotification) {
        // 获得rect
        let rect = notification.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        // 获取动画市场
        let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
        
        toolbarBottomCons?.constant = -UIScreen.mainScreen().bounds.height + rect.origin.y
        
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        textView.becomeFirstResponder()
    }
    
     // MARK: - 创建界面
    override func loadView() {
        view = UIView()
        
        view.backgroundColor = UIColor.whiteColor()
        
        // 将自动调整 scrollView 的缩进取消
        automaticallyAdjustsScrollViewInsets = false
        
        prepareNva()
        prepareToolBar()
        prepareTextView()
        preparePictureSelector()
        
    }
    
    private func preparePictureSelector() {
       
        // TODO:此处必须要添加
        addChildViewController(pictureSelectorVC)
        
        // 1.添加控制器
        view.insertSubview(pictureSelectorVC.view, belowSubview: toolBar)
    
        // 2.设置约束条件
        let size = UIScreen.mainScreen().bounds.size
        let w:CGFloat = size.width
        let h:CGFloat =  size.height * 0.4
        
       let cons =  pictureSelectorVC.view.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: w, height: h))
        
        pictureSelectorVC.view.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
        
        pictureHeightCons = pictureSelectorVC.view.ff_Constraint(cons, attribute: NSLayoutAttribute.Height)
        
    }
    
    // 准备输入的文本框
    private func prepareTextView() {
        
        view.addSubview(textView)
        
        // 设置自动布局
        textView.translatesAutoresizingMaskIntoConstraints = false 
        view.addConstraint(NSLayoutConstraint(item: textView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: topLayoutGuide, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 0))
        view.addConstraint(NSLayoutConstraint(item: textView, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Leading, multiplier: 1.0, constant: 0))
        view.addConstraint(NSLayoutConstraint(item: textView, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Width, multiplier: 1.0, constant: 0))
        
        textViewBottomCons =  NSLayoutConstraint(item: textView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: toolBar, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 0)
        view.addConstraint(textViewBottomCons!)
        
        // 设置占位标签 － 添加到 textView 就是为了保证能够同时滚动
        textView.addSubview(placeholderLabel)
        placeholderLabel.frame = CGRect(origin: CGPoint(x: 5, y: 8), size: placeholderLabel.bounds.size)
        textView.addSubview(placeholderLabel)
    }
  
    // 准备 ToolBar
    private func prepareToolBar() {
        
        // 定义按钮数组
        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background","action": "switchEmoticonKeyboard"],
            ["imageName": "compose_addbutton_background"]]
        
        // 定义一个存储所有item的数组
        var items = [UIBarButtonItem]()
        
        for dict in itemSettings {
            
            items.append(UIBarButtonItem(imageName: dict["imageName"]!, target: self, actionName: dict["action"]))
                
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        
        items.removeLast()
        toolBar.items = items
        view.addSubview(toolBar)
        
        // 设置 约束
        toolBar.translatesAutoresizingMaskIntoConstraints = false
        toolbarBottomCons =  NSLayoutConstraint(item: toolBar, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 0)
        view.addConstraint(toolbarBottomCons!)
        
        printLog(toolbarBottomCons)
        
        view.addConstraint(NSLayoutConstraint(item: toolBar, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Width, multiplier: 1.0, constant: 0))
        view.addConstraint(NSLayoutConstraint(item: toolBar, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: 44))
        view.addConstraint(NSLayoutConstraint(item: toolBar, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Leading, multiplier: 1.0, constant: 0))
    }
    
    
    // 准备 导航条
    private func prepareNva() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendStatus")
        navigationItem.rightBarButtonItem?.enabled = false
        
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 32))
        let titleLabel = UILabel(title: "发微博", color: UIColor.darkGrayColor(), fontSize: 15)
        let nameLabel = UILabel(title: UserAccountViewModel.sharedUserAccount.userAccount?.name, color: UIColor.lightGrayColor(), fontSize: 13)
        titleView.addSubview(titleLabel)
        titleView.addSubview(nameLabel)
        
        // 设置布局
        titleLabel.ff_AlignInner(type: ff_AlignType.TopCenter, referView: titleView, size: nil)
        nameLabel.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: titleView, size: nil)
        
        navigationItem.titleView = titleView
    }
    
     // MARK: - 懒加载控件
    private lazy var textView:UITextView = {
        let tv = UITextView()
        
        tv.delegate = self
        // 设置可以数值方向滚动
        tv.alwaysBounceVertical = true
        // 设置字体颜色
        tv.font = UIFont.systemFontOfSize(18)
        tv.textColor = UIColor.darkGrayColor()
        // 设置 当滚动的时候，关闭键盘
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        return tv
    }()
    
    
    private lazy var toolBar:UIToolbar = UIToolbar()
    /// 占位标签
    private lazy var placeholderLabel: UILabel = UILabel(title: "分享新鲜事...", color: UIColor.lightGrayColor(), fontSize: 18)
    /// 照片选择控制器
    private lazy var pictureSelectorVC = PictureSelectorViewController()
    
    // MARK: - 懒加载EmoticonController
    private lazy var keyBoadVC:EmoticonController = EmoticonController { [weak self](emoticon) -> () in
        
        self?.textView.insertEmoticon(emoticon)
    }
    
}
